package com.zhang.batchinsert;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCBatchInsert {
    public static final String URL = "jdbc:postgresql://192.168.29.18:5432/bigdata_source_local?reWriteBatchedInserts=true";
    private static String USERNAME = "postgres";
    private static String PWD = "postgres";

    public static void main(String[] args) {
        bulkSubmissionTest3();
    }

    public static void bulkSubmissionTest3() {
        Connection conn = null;
        PreparedStatement ps = null;

        long start = System.currentTimeMillis();
        //1. 导入驱动，加载具体的驱动类

        try {
            Class.forName("org.postgresql.Driver");
//            给Url，userName,Password赋值
            //2. 与数据库建立连接
            conn = DriverManager.getConnection(URL, USERNAME, PWD);
            String sql = "insert into test(id, name) VALUES (?,?)";
            ps = null;
            ps = (PreparedStatement) conn.prepareStatement(sql);
            for (int i = 1; i <= 100000; i++) {
                ps.setObject(1, i);
                ps.setObject(2, "小明" + i);
                ps.addBatch();
                if (i % 1000 == 0) {
                    ps.executeBatch();
                    ps.clearBatch();
                }
            }
            ps.executeBatch();
            ps.clearBatch();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        System.out.println("百万条数据插入用时：" + (System.currentTimeMillis() - start) + "【单位：毫秒】");
    }

}
